//
//  FileModelEntity.m
//  MultiMedia
//
//  Created by zorro on 14-12-5.
//  Copyright (c) 2014年 zorro. All rights reserved.
//

#import "FileModelEntity.h"
#import "YYJSONHelper.h"
#import "DownloadEntity.h"
#import "NSString+SBJSON.h"
#import "XYSandbox.h"
#import "AFNetworking.h"

#import "SNUserInfoModel.h"
#import "SportModel.h"
#import "SleepModel.h"
#import "HeartModel.h"
#import "OxModel.h"
#import "BpModel.h"

@implementation FileModelEntity

DEF_SINGLETON(FileModelEntity)

- (void)checkUpdateFirmwareInfo
{
    NSInteger saveAdv = [LASTCONNECTBLEHEAD getIntValue];
    if (saveAdv >0&& [HASLOGIN getBOOLValue]) {
     [self fileModelRequestWithBaseLink:@"/support/hwversion2" withRequestType:FileModelEntityRequestFirmware];
    }
}

//新的接口
- (void)fileModelRequestWithBaseLink:(NSString *)link withRequestType:(FileModelEntityRequest)requestType
{
        NSDictionary *dict = @{@"adv_id" : @(SN_USER.updateBleAdv),@"customid" : @(SN_USER.updateBleCustomerID)
                           };
//        NSLog(@"请求升级包接口dict>>>>>>>%@",dict);
        HttpRequest *hr = [self.requestHelper get:link params:dict];
        [hr succeed:^(MKNetworkOperation *op)
         {
           NSString *str = [op responseString];
//           NSLog(@"[op responseString] = ..%@", str);
             NSDictionary *dic = str.JSONValue;
             if (dic[@"ret"] && [dic[@"ret"] integerValue]==0)
             {
                 [self saveData:str withRequestType:requestType];
             }else{
                 return ;
             }
        } failed:^(MKNetworkOperation *op, NSError *err)
         {
//             SHOWMBProgressHUD(nil, err.localizedDescription, nil, NO, 2);
        }];

        [self.requestHelper submit:hr];
}

- (void)test:(NSString *)link dict:(NSDictionary *)dict
     success:(NSObjectSimpleBlock)success
        fail:(NSObjectSimpleBlock)fail
{
    [self.requestHelper emptyCache];
    
    HttpRequest *hr = [self.requestHelper post:link params:dict];
    NSLog(@"%@",hr);
    [hr succeed:^(MKNetworkOperation *op) {
        NSDictionary *dic = op.responseString.JSONValue;
        if (success) {
            success(dic);
        }
    } failed:^(MKNetworkOperation *op, NSError *err) {
        if (fail) {
            fail(nil);
        }
    }];
    
    [self.requestHelper submit:hr];
    hr.shouldContinueWithInvalidCertificate = YES;
}
- (void)gettest:(NSString *)link success:(NSObjectSimpleBlock)success
           fail:(NSObjectSimpleBlock)fail
{
    [self.requestHelper emptyCache];
    
    HttpRequest *hr = [self.requestHelper get:link params:nil];
    [hr succeed:^(MKNetworkOperation *op) {
        NSDictionary *dic = op.responseString.JSONValue;
        if (success) {
            success(dic);
        }
    } failed:^(MKNetworkOperation *op, NSError *err) {
        if (fail) {
            fail(nil);
        }
    }];
    
    [self.requestHelper submit:hr];
    hr.shouldContinueWithInvalidCertificate = YES;
}

- (void)userInfoTest:(NSString *)link dict:(NSDictionary *)dict success:(NSObjectSimpleBlock)success
                fail:(NSObjectSimpleBlock)fail
{
    [self.requestHelper emptyCache];
    HttpRequest *op = [self.requestHelper operationWithPath:link
                                                     params:dict
                                                 httpMethod:@"POST"];
    
    NSString *fullPath = [[XYSandbox libCachePath] stringByAppendingPathComponent:@"currentImages.jpg"];
    if (fullPath) {
        [op addFile:fullPath forKey:@"image"];
    }
    
    [op succeed:^(MKNetworkOperation *op) {
        NSDictionary *dic = op.responseString.JSONValue;
        if (success) {
            success(dic);
        }
    } failed:^(MKNetworkOperation *op, NSError *err) {
        if (fail) {
            fail(nil);
        }
    }];
    
    [self.requestHelper submit:op];
    op.shouldContinueWithInvalidCertificate = YES;
}

- (void)saveData:(NSString *)string withRequestType:(FileModelEntityRequest)requestType
{
    switch (requestType) {
        case FileModelEntityRequestFirmware: {
            _wareInfo = [string toModel:NSClassFromString(@"WareInfoModel") forKey:@"data"];
            [self isNeedDownloadWareZip];
            break;
        }
            
        default:
            break;
    }
}

- (void)isNeedDownloadWareZip
{
    if (_wareInfo)
    {
       NSLog(@"设备固件在线版本 >>%d 当前固件版本>>>%d",KK_BLEModel.bleOnlineVersion,KK_BLEModel.bleVersion);
        KK_BLEModel.bleOnlineVersion = _wareInfo.version.integerValue;
        
        if (KK_BLEModel.bleOnlineVersion == 0 && _wareInfo.download_url.length == 0) {
            return;
        }
        // 刷新设备界面是否有固件更新
        [[NSNotificationCenter defaultCenter]postNotificationName:@"GetUpdateFirmware" object:nil];
        if (KK_BLEModel.bleOnlineVersion > KK_BLEModel.bleVersion)
        {
            // 是否已经下载并进行了文件缓存.
            if (_wareInfo.isDownload) {
                NSString *fileName = [[_wareInfo.file componentsSeparatedByString:@"/"] lastObject];
                [DownloadEntity sharedInstance].filePath = [NSString stringWithFormat:@"%@/%@", [XYSandbox libCachePath], fileName];
            } else {
                // 没有下载就开始下载.
                if (_wareInfo.download_url.length > 0) {
                    [[DownloadEntity sharedInstance] downloadFileWithWebsite:_wareInfo.download_url
                                                             withRequestType:DownloadEntityRequestFirmware];
                }
                else
                {
                    SHOWMBProgressHUD(SN_Text(@"没有下载地址"), nil, nil, NO, 1.0);
                }
            }
        }
    }
}

- (void)requestSuccessWithString:(NSString *)string withRequestType:(FileModelEntityRequest)requestType
{
  
}

/*********************************************同步历史数据*****************************************************/

// 同步历史数据
- (void)GET:(NSString *)link params:(NSDictionary *)dict
    success:(NSObjectSimpleBlock)success
       fail:(NSObjectSimpleBlock)fail
{
    [self.requestHelper emptyCache];
    
    HttpRequest *hr = [self.requestHelper get:link params:dict];
    [hr succeed:^(MKNetworkOperation *op) {
        NSString *respon = op.responseString;
        if (success) {
            success(respon);
        }
    } failed:^(MKNetworkOperation *op, NSError *err) {
        if (fail) {
            fail(nil);
        }
    }];
    
    [self.requestHelper submit:hr];
}

//  同步网络数据
- (void)syncDataFromServer
{
    if (SN_USER.sport_days > 0 && SN_USER.sport_days > [SportModel localSportDays]) {
        [self downloadSport];
        [self downloadSleep];
        [self downloadExam:@"1"];
        [self downloadExam:@"2"];
        [self downloadExam:@"3"];
    }
}

// 运动
- (void)downloadSport
{
    if (SN_USER.create_time && SN_USER.access_token) {
        NSString *beginDate = [SN_USER.create_time componentsSeparatedByString:@" "][0];
        NSString *endDate = [[NSDate date] dateToDayString];
        
        NSDictionary *args = @{@"access_token" : SN_USER.access_token,
                               @"beginDate" : beginDate,
                               @"endDate" : endDate};
        
        [self GET:@"/sport/dates" params:args success:^(id object) {
            // object 为服务器运动数据对象数组
            NSString *respon = (NSString *)object;
            if ([respon rangeOfString:@"user_id"].length > 0) {
                NSArray *array = [respon toModels:SportModel.class forKey:@"data"];
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    for (SportModel *model in array) {
                        [model saveToDBByDownload];
                    }

                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (self.syncEnd) {
                            self.syncEnd(nil);
                        }
                    });

                });
            }
        } fail:^(id object) {
            
        }];
    }
}

// 睡眠
- (void)downloadSleep
{
    if (SN_USER.create_time && SN_USER.access_token) {
        NSString *beginDate = [SN_USER.create_time componentsSeparatedByString:@" "][0];
        NSString *endDate = [[NSDate date] dateToDayString];
        
        NSDictionary *args = @{@"access_token" : SN_USER.access_token,
                               @"beginDate" : beginDate,
                               @"endDate" : endDate};
        
        [self GET:@"/sleep/dates" params:args success:^(id object) {
            // object 为服务器睡眠数据对象数组
            NSString *respon = (NSString *)object;
            if ([respon rangeOfString:@"user_id"].length > 0) {
                NSArray *array = [respon toModels:SleepModel.class forKey:@"data"];
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    for (SleepModel *model in array) {
                        [model saveToDBByDownload];
                    }
                });
            }
        } fail:^(id object) {
            
        }];
    }
}

//  体检
- (void)downloadExam:(NSString *)type
{
    if (SN_USER.create_time && SN_USER.access_token) {
        NSString *beginDate = [SN_USER.create_time componentsSeparatedByString:@" "][0];
        NSString *endDate = [[NSDate date] dateToDayString];
        
        NSDictionary *args = @{@"access_token" : SN_USER.access_token,
                               @"beginDate" : beginDate,
                               @"endDate" : endDate,
                               @"type" : type};
        
        [self GET:@"/examination/dates2" params:args success:^(id object) {
            // object 为服务器体检数据对象数组
            NSString *respon = (NSString *)object;
            if ([respon rangeOfString:@"user_id"].length > 0) {
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    if (type.integerValue == 1) {
                        NSArray *array = [respon toModels:OxModel.class forKey:@"data"];
                        for (OxModel *model in array) {
                            [model saveToDBByDownload];
                        }
                    } else if (type.integerValue == 2) {
                        NSArray *array = [respon toModels:HeartModel.class forKey:@"data"];
                        for (HeartModel *model in array) {
                            [model saveToDBByDownload];
                        }
                    } else if (type.integerValue == 3) {
                        NSArray *array = [respon toModels:BpModel.class forKey:@"data"];
                        for (BpModel *model in array) {
                            [model saveToDBByDownload];
                        }
                    }
                });
            }
        } fail:^(id object) {
            
        }];
    }
}

@end
